﻿import socket
import threading


# -------------------------------------------------------
# 后台线程：读取服务器控制台输入并广播给所有客户端
# -------------------------------------------------------
def broadcast_input(clients):
    while True:
        try:
            text = input()  # 等价于 getStdIn().readln()
            data = text.encode("utf-8")

            # 向所有客户端广播
            for client in list(clients):
                try:
                    client.send(data)
                except:
                    clients.remove(client)
        except Exception as e:
            print("输入广播失败:", e)
            break


# -------------------------------------------------------
# 每个客户端的接收线程
# -------------------------------------------------------
def handle_client(client_socket, clients):
    while True:
        try:
            data = client_socket.recv(1024)
            if not data:
                print("客户端断开连接")
                break

            print(data.decode("utf-8"))

        except Exception as e:
            print("客户端连接异常:", e)
            break

    # 移除断开的客户端
    if client_socket in clients:
        clients.remove(client_socket)
    client_socket.close()


# -------------------------------------------------------
# 主服务器程序
# -------------------------------------------------------
def main():
    host = "0.0.0.0"
    port = 8080

    # 创建 TCP 服务器
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((host, port))
    server.listen()

    print("开始监听：", port)

    # 所有已连接的客户端
    clients = []

    # 启动广播线程（服务器控制台输入 → 所有客户端）
    input_thread = threading.Thread(target=broadcast_input, args=(clients,))
    input_thread.daemon = True
    input_thread.start()

    # 主循环：接受连接
    while True:
        client_socket, addr = server.accept()
        print("新客户端连接：", addr)
        clients.append(client_socket)

        # 为当前客户端开启线程处理消息
        thread = threading.Thread(target=handle_client, args=(client_socket, clients))
        thread.daemon = True
        thread.start()


if __name__ == "__main__":
    main()
